package fei.yuzhi.com.loveflowers.fragment.firstpagefragment.detail.baseinformation;

import android.content.Intent;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.j256.ormlite.dao.Dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import fei.yuzhi.com.loveflowers.R;
import fei.yuzhi.com.loveflowers.bean.firstpagedetailbean.GoodsCommendListBean;
import fei.yuzhi.com.loveflowers.fragment.firstpagefragment.detail.DetailActivity;

import fei.yuzhi.com.loveflowers.fragment.shopping.ShoppingBean;
import fei.yuzhi.com.loveflowers.fragment.shopping.ShoppingHelper;
import fei.yuzhi.com.loveflowers.utils.MyGridView;

/**
 * Created by My on 2016/10/8.
 */
public class BaseInformationFragment extends Fragment implements BaseInfomationContract
        .IBaseInformationView{
    @BindView(R.id.firstpage_detail_base_goodsimage)
    ImageView firstpageDetailBaseGoodsimage;
    @BindView(R.id.firstpage_detail_base_store_name)
    TextView firstpageDetailBaseStoreName;
    @BindView(R.id.firstpage_detail_base_goods_name)
    TextView firstpageDetailBaseGoodsName;
    @BindView(R.id.firstpage_detail_base_goods_promotion_price)
    TextView firstpageDetailBaseGoodsPromotionPrice;
    @BindView(R.id.firstpage_detail_base_goods_marketprice)
    TextView firstpageDetailBaseGoodsMarketprice;
    @BindView(R.id.firstpage_detail_base_goods_price)
    TextView firstpageDetailBaseGoodsPrice;
    @BindView(R.id.firstpage_detail_base_gv)
    MyGridView firstpageDetailBaseGv;
    @BindView(R.id.firstpage_detail_base_allsale)
    TextView firstpageDetailBaseAllsale;
    @BindView(R.id.firstpage_detail_base_allgoods)
    TextView firstpageDetailBaseAllgoods;
    @BindView(R.id.firstpage_detail_base_collect)
    ImageView firstpageDetailBaseCollect;
    @BindView(R.id.firstpage_detail_base_des)
    TextView firstpageDetailBaseDes;
    @BindView(R.id.firstpage_detail_base_add)
    TextView firstpageDetailBaseAdd;
    @BindView(R.id.firstpage_detail_base_buynum)
    TextView firstpageDetailBaseBuynum;


    private String data;
    private BaseInformationPresenter presenter;
    private Handler handler = new Handler();
    TextView tv_good_fitting_num;
    TextView tv_goods_car_nums;
    private ShoppingHelper helper;
    private Dao<ShoppingBean, Integer> shoppingDao;
    private List<ShoppingBean> shoppingBeanList=new ArrayList<>();


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
    Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout
                .fragment_firstpage_detail_base, null);
        initHelper();
        ButterKnife.bind(this, view);
        tv_good_fitting_num = (TextView) getActivity().findViewById(R.id.tv_good_fitting_num);
        tv_goods_car_nums= (TextView) getActivity().findViewById(R.id.tv_goods_car_nums);
        presenter = new BaseInformationPresenter(this);
        Intent intent = getActivity().getIntent();
        data = intent.getStringExtra("data");
        Log.i("tag", "------------------>" + data);
        presenter.getBean(data);
        return view;
    }

    @Override
    public void getBeanSuccess(final String goodsImageUrl, final Map<String, String> mTextViewMap,
                               final List<GoodsCommendListBean> commendListBeen) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                //将商品地址地址添加到控件中
                if (goodsImageUrl != null) {
                    Glide.with(getActivity()).load(goodsImageUrl).into
                            (firstpageDetailBaseGoodsimage);
                }
                //通过传递的map集合数据得到店铺名
                String store_name=mTextViewMap.get("Store_name");
                firstpageDetailBaseStoreName.setText("[" + store_name + "]");
                //得到商品名
                final String goods_name=mTextViewMap.get("Goods_name");
                firstpageDetailBaseGoodsName.setText(goods_name);
                if (mTextViewMap.get("goods_price") != null) {//判空
                    //将原售价添加到控件中
                    String goods_price=mTextViewMap.get("goods_price");
                    firstpageDetailBaseGoodsPrice.setText(getResources().getString(R.string
                            .first_base_lastprice) + goods_price + ")");
                }
                //将市场价添加到控件中
                String goods_marketprice=mTextViewMap.get("Goods_marketprice");
                firstpageDetailBaseGoodsMarketprice.setText(getResources().getString(R.string
                        .first_base_marcketprice) + goods_marketprice);
                //将现售价添加到控件中
                final String goods_promotion_price=mTextViewMap.get("goods_promotion_price");
                firstpageDetailBaseGoodsPromotionPrice.setText("￥" +goods_promotion_price );
                //设置textview的中间划线，实现划掉市场价的效果
                firstpageDetailBaseGoodsMarketprice.getPaint().setFlags(Paint
                        .STRIKE_THRU_TEXT_FLAG);
                //将得到的集合数据添加到gridview适配器中
                BaseInformationAdapter adapter = new BaseInformationAdapter(getActivity(),
                        commendListBeen);
                firstpageDetailBaseGv.setAdapter(adapter);
                firstpageDetailBaseAllgoods.setText(mTextViewMap.get("goods_storage"));
                Log.i("tag", "==lala==" + mTextViewMap.get("goods_storage"));
                firstpageDetailBaseAllsale.setText(mTextViewMap.get("goods_salenum"));
                final int storage = Integer.parseInt(mTextViewMap.get("goods_storage"));
                firstpageDetailBaseAdd.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int buyNum = Integer.parseInt((String) firstpageDetailBaseBuynum.getText());
                        if (buyNum < storage) {
                            buyNum += 1;
                            firstpageDetailBaseBuynum.setText(buyNum + "");
                        } else {
                            Toast.makeText(getActivity(), "数量已经达到上限", Toast.LENGTH_SHORT).show();
                        }
                        //添加购物车时小球的动画
                        NXHooldeView nxHooldeView = new NXHooldeView(getActivity());
                        int position[] = new int[2];
                        firstpageDetailBaseAdd.getLocationInWindow(position);
                        nxHooldeView.setStartPosition(new Point(position[0], position[1]));
                        ViewGroup rootView = (ViewGroup) getActivity().getWindow().getDecorView();
                        rootView.addView(nxHooldeView);
                        int endPosition[] = new int[2];
                        tv_good_fitting_num.getLocationInWindow(endPosition);
                        tv_good_fitting_num.setText(buyNum + "");
                        nxHooldeView.setEndPosition(new Point(endPosition[0], endPosition[1]));
                        nxHooldeView.startBeizerAnimation();
                    }
                });
                //绑定数量减少按钮的单击事件
                firstpageDetailBaseDes.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int buyNum = Integer.parseInt((String) firstpageDetailBaseBuynum.getText());
                        if (buyNum >= 1) {
                            buyNum -= 1;
                            firstpageDetailBaseBuynum.setText(buyNum + "");
                        } else {
                            Toast.makeText(getActivity(), "数量不能小于0", Toast.LENGTH_SHORT).show();
                        }
                        tv_good_fitting_num.setText(buyNum + "");
                    }
                });
                //绑定下面商品列表的单击事件
                firstpageDetailBaseGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long
                            id) {
                        Intent intent = new Intent(getActivity(), DetailActivity.class);
                        intent.putExtra("data", commendListBeen.get(position).getGoods_id());
                        startActivity(intent);
                    }
                });

                //绑定购物车的单击事件
                tv_goods_car_nums.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                        double price=Double.parseDouble(goods_promotion_price);
                        int buyNum = Integer.parseInt((String) firstpageDetailBaseBuynum.getText());

                            shoppingBeanList = shoppingDao.queryBuilder().where().eq("data", BaseInformationFragment.this.data).query();
                            if (shoppingBeanList.size()==0) {
                                ShoppingBean shoppingBean = new ShoppingBean(BaseInformationFragment.this.data, goods_name, price, storage, buyNum, goodsImageUrl, true);
                               // Log.i("tag", "--+++++-->" + BaseInformationFragment.this.data + "??" + goods_name + "??" + price + "??" + storage + "??" + buyNum + "??" + goodsImageUrl);

                                int i = shoppingDao.create(shoppingBean);
                                Toast.makeText(getContext(), "添加商品成功", Toast.LENGTH_SHORT).show();
                            }else {
                                Toast.makeText(getContext(), "您已添加过本商品", Toast.LENGTH_SHORT).show();
                            }

                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                });

                firstpageDetailBaseCollect.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        double price=Double.parseDouble(goods_promotion_price);
                        int buyNum = Integer.parseInt((String) firstpageDetailBaseBuynum.getText());

                    }
                });
            }
        });
    }


    //
    @Override
    public void getBeanFail(String msg) {
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
        Log.i("tag", msg);
    }
    private void initHelper() {

        try {
            helper = ShoppingHelper.getInstamce(getContext());
            shoppingDao = helper.getDao(ShoppingBean.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


}
